<template>
  <el-alert type="warning" closable
    >请注意：在使用VOS点呼/群呼，双向回拨业务之前，需提交主叫号码加白审批，
    在《加白审批管理》中添加话术，待审批通过后才可拨打</el-alert
  >
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="100px"
      label-position="left"
    >
      <el-form-item label="坐席工号" prop="agentNumber">
        <el-input
          v-model="queryParams.agentNumber"
          placeholder="请输入坐席工号"
          clearable
          @keyup.enter="handleQuery"
          class="!w-260px"
        />
      </el-form-item>
      <el-form-item label="负责人" prop="ownerUserId">
        <el-select v-model="queryParams.ownerUserId" clearable filterable>
          <el-option
            v-for="item in userOptions"
            :key="parseInt(item.id)"
            :label="item.nickname"
            :value="parseInt(item.id)"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="外呼手机" prop="telephone">
        <el-input
          v-model="queryParams.telephone"
          placeholder="请输入外呼手机"
          clearable
          @keyup.enter="handleQuery"
          class="!w-260px"
        />
      </el-form-item>
      <el-form-item label="真实姓名" prop="realName">
        <el-input
          v-model="queryParams.realName"
          placeholder="请输入真实姓名"
          clearable
          @keyup.enter="handleQuery"
          class="!w-260px"
        />
      </el-form-item>
      <el-form-item label="创建时间" prop="createTime">
        <el-date-picker
          v-model="queryParams.createTime"
          value-format="YYYY-MM-DD HH:mm:ss"
          type="daterange"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
          class="!w-240px"
        />
      </el-form-item>
    </el-form>
    <div class="flex justify-between">
      <div>
        <el-button @click="handleQuery"><Icon icon="ep:search" class="mr-5px" /> 搜索</el-button>
        <el-button @click="resetQuery"><Icon icon="ep:refresh" class="mr-5px" /> 重置</el-button>
        <el-button type="success" plain @click="onPayment('call-agent')" :loading="exportLoading">
          <Icon icon="ep:goods-filled" class="mr-5px" /> 购买坐席
        </el-button>
        <el-button
          type="success"
          plain
          @click="beforePayment('simple-call', 1)"
          :loading="exportLoading"
          :disabled="multipleSelection.length == 0"
        >
          <Icon icon="ep:goods-filled" class="mr-5px" /> 购买点呼话费
        </el-button>
        <el-button
          type="success"
          plain
          @click="beforePayment('double-call', 1)"
          :loading="exportLoading"
          :disabled="multipleSelection.length == 0"
        >
          <Icon icon="ep:goods-filled" class="mr-5px" /> 购买双呼话费
        </el-button>
      </div>
    </div>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table
      v-loading="loading"
      :data="list"
      :stripe="true"
      :show-overflow-tooltip="true"
      @selection-change="handleSelectionChange"
      border
    >
      <el-table-column type="selection" width="55" />
      <el-table-column label="坐席工号" align="center" prop="agentNumber" width="120" />
      <el-table-column label="负责人" align="center" prop="ownerUsername" width="120" />

      <el-table-column label="点呼主叫加白" align="center" prop="sipCallAuditStatus" width="120">
        <template #default="scope">
          <div>
            <el-tag
              v-if="auditStatusMap[scope.row.sipCallAuditStatus]"
              :type="auditStatusMap[scope.row.sipCallAuditStatus].type"
              >{{ auditStatusMap[scope.row.sipCallAuditStatus].text }}</el-tag
            >
          </div>
        </template>
      </el-table-column>
      <el-table-column label="双向回拨加白" align="center" prop="doubleCallAuditStatus" width="120">
        <template #default="scope">
          <div>
            <el-tag
              v-if="auditStatusMap[scope.row.doubleCallAuditStatus]"
              :type="auditStatusMap[scope.row.doubleCallAuditStatus].type"
              >{{ auditStatusMap[scope.row.doubleCallAuditStatus].text }}</el-tag
            >
          </div>
        </template>
      </el-table-column>

      <el-table-column label="状态" align="center" prop="status" width="120">
        <template #default="scope">
          <el-tag type="info" v-if="scope.row.status == 0">未启用</el-tag>
          <el-tag type="success" v-if="scope.row.status == 1">已启用</el-tag>
          <el-tag type="danger" v-if="scope.row.status == 9">已过期</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="第一班组" align="center" prop="groupName" width="120">
      </el-table-column>
      <el-table-column label="第二班组" align="center" prop="secGroupName" width="120">
      </el-table-column>
      <el-table-column label="有效期" align="center" prop="expireTime" width="180">
        <template #default="scope">
          <span v-if="scope.row.expireTime == 0">永久</span>
          <span v-else>至：{{ formatDate(scope.row.expireAt) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="双呼主叫手机号" align="center" prop="telephone" width="150" />

      <el-table-column label="真实姓名" align="center" prop="realName" width="220">
        <template #default="scope">
          <div v-if="scope.row.realName != null">
            {{ scope.row.realName }}
          </div>
          <div v-if="scope.row.realName == null">
            <el-input
              maxlength="10"
              clearable
              v-if="scope.row.isShowRealNameInput == true"
              v-model.trim="scope.row.realNameValue"
              class="w-120px!"
              placeholder="请输入真实姓名"
            />
            <el-icon
              v-if="!scope.row.isShowRealNameInput"
              @click="scope.row.isShowRealNameInput = !scope.row.isShowRealNameInput"
              :size="12"
              color="green"
              class="cursor-pointer"
            >
              <Plus />
            </el-icon>
            <el-icon
              v-if="scope.row.isShowRealNameInput"
              @click="handleSaveName(scope.row.realNameValue, scope.row, 'name')"
              :size="12"
              color="green"
              class="cursor-pointer px-10px"
            >
              <Select />
            </el-icon>
            <el-icon
              v-if="scope.row.isShowRealNameInput"
              @click="scope.row.isShowRealNameInput = !scope.row.isShowRealNameInput"
              :size="12"
              color="green"
              class="cursor-pointer pl-0px"
            >
              <CloseBold />
            </el-icon>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="身份证号" align="center" prop="idNumber" width="280">
        <template #default="scope">
          <div v-if="scope.row.idNumber != null">
            {{ scope.row.idNumber }}
          </div>
          <div v-if="scope.row.idNumber == null">
            <el-input
              maxlength="18"
              clearable
              v-if="scope.row.isShowIdNumberInput == true"
              v-model.trim="scope.row.idNumberValue"
              class="w-200px!"
              placeholder="请输入身份证号"
            />
            <el-icon
              v-if="!scope.row.isShowIdNumberInput"
              @click="scope.row.isShowIdNumberInput = !scope.row.isShowIdNumberInput"
              :size="12"
              color="green"
              class="cursor-pointer"
            >
              <Plus />
            </el-icon>
            <el-icon
              v-if="scope.row.isShowIdNumberInput"
              @click="handleSaveName(scope.row.idNumberValue, scope.row, 'idNumber')"
              :size="12"
              color="green"
              class="cursor-pointer px-10px"
            >
              <Select />
            </el-icon>
            <el-icon
              v-if="scope.row.isShowIdNumberInput"
              @click="scope.row.isShowIdNumberInput = !scope.row.isShowIdNumberInput"
              :size="12"
              color="green"
              class="cursor-pointer px-0px"
            >
              <CloseBold />
            </el-icon>
          </div>
        </template>
      </el-table-column>
      <el-table-column
        label="创建时间"
        align="center"
        prop="createTime"
        :formatter="dateFormatter"
        width="180px"
      />

      <el-table-column label="操作" align="center" width="200" fixed="right">
        <template #default="scope">
          <el-button type="primary" link @click="showPackage(scope.row)">套餐余额</el-button>
          <el-button
            link
            type="success"
            :disabled="scope.row.expireTime == 0"
            @click="onRenew('call-agent', scope.row.id)"
            v-hasPermi="['call:agent:update']"
          >
            续费
          </el-button>
          <!-- <el-button
            link
            type="success"
            @click="onPayment('simple-call', 1)"
            v-hasPermi="['call:agent:update']"
          >
            双呼报白
          </el-button> -->
          <el-button
            link
            type="primary"
            @click="openForm('update', scope.row.id)"
            v-hasPermi="['call:agent:update']"
          >
            编辑
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

  <!-- 表单弹窗：添加/修改 -->
  <AgentForm ref="formRef" @success="getList" />

  <!-- 购买套餐弹窗 -->
  <SkuFormDialog ref="skuFormDialog" />

  <!-- 续费弹窗 -->
  <RenewPackageDialog ref="renewPackgeRef" />

  <!-- 套餐余额 -->
  <PackagePalance ref="tablePackage" />
</template>

<script setup lang="ts">
import SkuFormDialog from '@/components/SkuFormDialog/index.vue'
import RenewPackageDialog from '@/components/RenewPackageDialog/index.vue'
import { dateFormatter, formatDate } from '@/utils/formatTime'
import * as AgentApi from '@/api/call/agent'
import AgentForm from './AgentForm.vue'
import { Plus, Select, CloseBold } from '@element-plus/icons-vue'
import * as UserApi from '@/api/system/user'
import PackagePalance from '@/components/PackagePalance/index.vue'
import { CACHE_KEY, useCache } from '@/hooks/web/useCache'
const { wsCache } = useCache('localStorage')

const userOptions = ref<UserApi.UserVO[]>([]) // 用户列表

defineOptions({ name: 'Agent' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const loading = ref(true) // 列表的加载中
const list = ref([]) // 列表的数据
const total = ref(0) // 列表的总页数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  agentNumber: undefined,
  telephone: undefined,
  realName: undefined,
  createTime: [],
  ownerUserId: ''
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中
const auditStatusMap = {
  0: { type: 'info', text: '待审批' },
  1: { type: 'success', text: '已加白' },
  2: { type: 'danger', text: '不通过' }
}
// 选择坐席
const multipleSelection = ref([])
const handleSelectionChange = (val) => {
  multipleSelection.value = val
}
/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await AgentApi.getAgentPage(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id)
}

const handleSaveName = async (val, row, field) => {
  if (field == 'name') {
    if (val) {
      row.realName = val
    } else {
      message.error('请输入真实姓名')
      return
    }
  }
  if (field == 'idNumber') {
    let idReg =
      /(^[1-9]\d{5}(18|19|([23]\d))\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$)|(^[1-9]\d{5}\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{2}$)/
    if (idReg.test(val) != true) {
      message.error('请输入有效的身份证号码！')
      return
    } else {
      row.idNumber = val
    }
  }
  await AgentApi.updateAgent(row)
  message.success(t('common.updateSuccess'))
  row.isShowRealNameInput = false
}

// 支付前置操作
const beforePayment = async (type, number) => {
  // 验证所选坐席是否绑定了负责人， 验证所选坐席sip是否加白
  let newList = multipleSelection.value.filter((v) => {
    return v.ownerUserId != null && v.ownerUserId != 0 && v.ownerUserId != ''
  })
  if (newList.length == 0) {
    message.error('所选坐席必须有指定的负责人')
    return
  } else {
    message.success('已自动过滤掉未分配负责人的坐席')
  }
  if (type == 'simple-call') {
    const unAuditList = newList.filter((v) => v.sipCallAuditStatus != 1)
    if (unAuditList.length > 0) {
      // 弹窗提示用户
      await message.confirm('所选坐席中存在未审核主叫加白的记录，是否继续购买？', '提示')
    }
  } else if (type == 'double-call') {
    const unAuditList = newList.filter((v) => v.doubleCallAuditStatus != 1)
    if (unAuditList.length > 0) {
      // 弹窗提示用户
      await message.confirm('所选坐席中存在未审核主叫加白的记录，是否继续购买？', '提示')
    }
  }
  onPayment(
    type,
    number,
    newList.map((v) => v.ownerUserId)
  )
}

const skuFormDialog = ref()
// 吊起支付方法
const onPayment = (code: string, type?: number = 2, userIdList) => {
  skuFormDialog.value.open(type, code, null, userIdList)
}

const renewPackgeRef = ref()
// 吊起续费方法
const onRenew = (code: string, rowId) => {
  renewPackgeRef.value.open(code, rowId)
}
const getUserOptions = async () => {
  userOptions.value = await UserApi.getSimpleUserList()
}

const tablePackage = ref(null)
/*套餐余额*/
const showPackage = (item) => {
  tablePackage.value.open(item.ownerUserId, wsCache.get(CACHE_KEY.TenantId))
}
/** 初始化 **/
onMounted(() => {
  getList()
  getUserOptions()
})
</script>
